package com.yangxk.kadmin.generator.engine;

import com.yangxk.kadmin.generator.genfile.GeneratorFile;
import com.yangxk.kadmin.generator.constant.Const;
import com.yangxk.kadmin.generator.constant.Vue;
import com.yangxk.kadmin.generator.internal.ConfigInternal;
import com.yangxk.kadmin.generator.util.Tools;

import java.io.*;
import java.util.*;

import static com.yangxk.kadmin.generator.util.Tools.first2Lower;

public class SimpleTemplateEngine extends AbstractTemplateEngine {

    @Override
    public void generatorVueRoute(ConfigInternal configInternal) {
        String vueProjectPath = configInternal.getVueProjectPath();
        File routeFile = new File(vueProjectPath + File.separator + Vue.VUE_ROUTE_PATH, Vue.VUE_ROUTE_NAME);
        System.out.println(routeFile.getAbsolutePath());
        File tmp = new File(vueProjectPath + File.separator + Vue.VUE_ROUTE_PATH, "tmp.js");

        try (
            BufferedReader br = new BufferedReader(new FileReader(routeFile));
            BufferedWriter bw = new BufferedWriter(new FileWriter(tmp));
        ) {
            String line = "";
            String addContent = "";
            while ((line = br.readLine()) != null) {
                if (line.trim().equals("}// route")) {
                    addContent = writeRoute(bw, configInternal);
                }
                bw.write(line);
                bw.newLine();
            }

            bw.close();
            br.close();

            routeFile.delete();
            tmp.renameTo(new File(routeFile.getAbsolutePath()));

            generatorFiles.add(new GeneratorFile(Vue.VUE_ROUTE_NAME, routeFile.getAbsolutePath(), true, addContent));
        } catch (Exception e) {

        }
    }

    private String writeRoute(BufferedWriter bw, ConfigInternal configInternal) {
        Map<String, String> url = configInternal.getRequestUrl();
        String begin = "}, { // " + configInternal.getZhModelName();
        String path = "  path: '" + url.get(Const.ROUTE) + "',"; // 2个空格
        String name = "  name: '" + Tools.first2Lower(configInternal.getModelName()) + "List',";
        String component = "  component: () => import('@/" + Vue.VUE_PAGE_DIR + "/" + first2Lower(configInternal.getModelName()) + "/" + configInternal.getNames().get(Const.VUE_PAGE_NAME) + "')";
        try {
            bw.write(begin); // 8个空格
            bw.newLine();

            bw.write(path);
            bw.newLine();

            bw.write(name);
            bw.newLine();

            bw.write(component);
            bw.newLine();

            StringBuilder sb = new StringBuilder();
            sb.append(begin);
            sb.append("###");

            sb.append(path);
            sb.append("###");

            sb.append(name);
            sb.append("###");

            sb.append(component);

            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

 }
